package com.ssy.lingxi.order.handler.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据库Jsonb字段与Map<String, Object>的转换
 * @author 万宁
 * @version 2.0.0
 * @date 2021-07-17
 */
@Converter(autoApply = true)
public class JpaJsonToMapConverter implements AttributeConverter<Map<String,Object>, String> {
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 将Map转换为数据库Json字段
     * @param attribute 自定义Map对象
     * @return Json字符串
     */
    @Override
    public String convertToDatabaseColumn(Map<String, Object> attribute) {
        try {
            if(attribute == null) {
                return OBJECT_MAPPER.writeValueAsString(new HashMap<>());
            }

            return OBJECT_MAPPER.writeValueAsString(attribute);
        } catch (JsonProcessingException ex) {
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"数据库Json字段写入错误");
        }
    }

    /**
     * 将数据库Json字段转换为Map
     * @param dbData 数据库jsonb字段Json字符串
     * @return Map对象
     */
    @Override
    public Map<String, Object> convertToEntityAttribute(String dbData) {
        try {
            if(dbData == null) {
                return new HashMap<>();
            }

            return OBJECT_MAPPER.readValue(dbData, new TypeReference<Map<String, Object>>() {});
        } catch (JsonProcessingException ex) {
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"数据库Json字段反序列化错误");
        }
    }
}
